import Snake from './snake'
import Food from './Food'
import ScopePanel from './ScopePanel'

class GameControl{
  snake:Snake;
  food:Food;
  scopePanel:ScopePanel;

  direction:string='';

  isLive:boolean=true;

  constructor(){
    this.snake= new Snake();
    this.food = new Food();
    this.scopePanel = new ScopePanel();
    this.init();
  }

  init(){
    document.addEventListener("keydown",(event:KeyboardEvent)=>{
      this.direction=event.key;
      // console.log(this.direction);
      
    })
    this.run();
  }

  run(){
    let x=this.snake.X;
    let y=this.snake.Y;

    switch (this.direction) {
      case "ArrowUp": y-=10;
        break;
      case "ArrowDown": y+=10;
          break;
      case "ArrowLeft": x-=10;
          break;
      case "ArrowRight": x+=10;
          break;
    }
    if(this.checkEat(x,y)){
      this.food.change();
      this.scopePanel.addScore();
      this.snake.addBody()
      // console.log('吃到食物了！');
    }
    try{
      this.snake.X=x;
      this.snake.Y=y;
      }catch(e){
        alert(e.message)
        this.isLive=false
      }

    this.isLive && setTimeout(this.run.bind(this), 300-(this.scopePanel.level-1)*30);
  }

  checkEat(X:number,Y:number){
    return X===this.food.X && Y===this.food.Y
  }


}

export default GameControl;